package com.sjz.yuyin;

import net.sourceforge.pinyin4j.PinyinHelper;

/**
 * 中文转换成拼音
 * @author Administrator
 *
 */
public class ChineseToPinyin {
	public static void main(String[] args) {
		/**
         String chinese = "你好，世界！ 王冬 冬天 ";
         String pinyin = convertToPinyin(chinese);
         System.out.println(pinyin);
		**/
		 ctp(); /**/
    }
 
	/***
	 * 显示声调
	 * @param chinese
	 * @return
	 */
    public static String convertToPinyin(String chinese) {
        StringBuilder pinyin = new StringBuilder();
        char[] chars = chinese.toCharArray();
 
        for (char c : chars) {
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
 
            if (pinyinArray != null) {
                pinyin.append(pinyinArray[0]);
            } else {
                pinyin.append(c);
            }
        }
        //ni3hao3，shi4jie4！ wang2dong1  数字指的是声调
        return pinyin.toString();
    } 
    
    
    /***
     * 设置不带声调
     */
    public static void ctp() {
    	  String input = "你好,世界！";
          // 设置不带声调的输出选项
          net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat format = new net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat();
          format.setToneType(net.sourceforge.pinyin4j.format.HanyuPinyinToneType.WITHOUT_TONE);
   
          StringBuilder output = new StringBuilder();
          for (char c : input.toCharArray()) {
              try {
                  String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                  if (pinyinArray != null && pinyinArray.length > 0) {
                      output.append(pinyinArray[0]).append("");
                  } else {
                      output.append(c).append("");
                  }
              } catch (Exception e) {
                  output.append(c).append("");
              }
          }
   
          System.out.println(output.toString().trim()); // 输出结果：nihao,shijie！
    }
}
